<?php
declare (strict_types = 1);

namespace app\model;

use app\BaseModel;
use app\model\NoteDrawItem;

/**
 * NoteDraw模型
 */
class NoteDraw extends BaseModel
{
    // 设置表名
    protected $name = 'note_draws';
    
    // 设置字段信息
    protected $schema = [
        'id'               => 'int',
        'user_id'          => 'int',
        'note_id'          => 'int',
        'order_id'         => 'string',
        'draw_type'        => 'int',
        'draw_count'       => 'int',
        'amount'           => 'float',
        'status'           => 'int',
        'pay_time'         => 'datetime',
        'create_time'      => 'datetime',
        'update_time'      => 'datetime',
    ];
    
    // 设置自动时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 获取抽取类型文本
     */
    public function getDrawTypeTextAttr()
    {
        $types = [1 => '单抽', 2 => '多抽'];
        return $types[$this->draw_type] ?? '未知';
    }
    
    /**
     * 获取支付状态文本
     */
    public function getStatusTextAttr()
    {
        $statuses = [0 => '未支付', 1 => '已支付'];
        return $statuses[$this->status] ?? '未知';
    }
    
    /**
     * 获取抽取用户
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    
    /**
     * 获取抽取的纸条
     */
    public function note()
    {
        return $this->belongsTo(Note::class, 'note_id', 'id');
    }
    
    /**
     * 获取多抽时的所有抽取纸条
     * 关联note_draw_items表和notes表获取多抽的纸条列表
     */
    public function drawnNotes()
    {
        if ($this->draw_type == 1) {
            // 单抽，直接关联note
            return $this->belongsTo(Note::class, 'note_id', 'id');
        } else {
            // 多抽，通过中间表关联
            return $this->belongsToMany(Note::class, 'note_draw_items', 'draw_id', 'note_id');
        }
    }
    
    /**
     * 设置订单为已支付
     */
    public function setPaid()
    {
        return $this->save([
            'status' => 1,
            'pay_time' => date('Y-m-d H:i:s')
        ]);
    }
} 